package com.ygl.strategy.service.tracer;

import com.nepxion.matrix.proxy.aop.AbstractInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: yanggld
 * date: 2019/12/22 19:46
 * version: 1.0
 * description: ServiceStrategyTracerInterceptor
 */
public class ServiceStrategyTracerInterceptor extends HandlerInterceptorAdapter {

    @Autowired(required = false)
    private List<ServiceStrategyTracer> serviceStrategyTracerList;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 调用链追踪
                if (CollectionUtils.isNotEmpty(serviceStrategyTracerList)) {
                    for (ServiceStrategyTracer serviceStrategyTracer : serviceStrategyTracerList) {
                        serviceStrategyTracer.trace(handlerMethod);
                    }
                }
            }
            return super.preHandle(request, response, handler);
        } catch (Throwable e) {
            throw e;
        } finally {
            if (CollectionUtils.isNotEmpty(serviceStrategyTracerList)) {
                for (ServiceStrategyTracer serviceStrategyTracer : serviceStrategyTracerList) {
                    serviceStrategyTracer.release(null);
                }
            }
        }
    }

    private Map<String, String> getCustomizationMap() {
        Map<String, String> map = new HashMap<>();
        map.put("ygl", "adadad");
        return map;
    }
}
